package com.youdoneed.user.admin;

import com.youdoneed.base.application.ResultMessage;
import com.youdoneed.base.common.JWTUtils;
import com.youdoneed.base.common.RSAEncryptor;
import com.youdoneed.base.pagination.Page;
import com.youdoneed.base.pagination.Paging;
import com.youdoneed.user.application.ExcelUtils;
import com.youdoneed.user.consts.UserConst;
import com.youdoneed.user.model.Admin;
import com.youdoneed.user.model.Authority;
import com.youdoneed.user.model.User;
import com.youdoneed.user.user.UserService;
import com.youdoneed.user.vo.FindUserParam;
import com.youdoneed.user.vo.UserBasicInfo;
import com.youdoneed.user.vo.UserStatistics;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 管理员用户模块请求控制器
 *
 * @author Ewing
 * @date 2017年2月8日
 */
@RestController
@RequestMapping("/admin")
@Api(description = "管理员功能")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;

    /**
     * 获取管理员用户
     *
     * @param name 管理员用户名称
     * @return ResultMessage
     */
    @RequestMapping(value = "/queryAdmin", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage<Page<Admin>> queryAdmin(Paging param, String name) {
        Page<Admin> adminPage = adminService.findAdminByName(name, param);
        return new ResultMessage<>(adminPage);
    }

    /**
     * 修改管理员用户
     */
    @RequestMapping(value = "/updateAdmin", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage updateAdmin(Admin admin, @RequestParam(value = "roleIds[]") String[] roleIds) {
        adminService.updateAdmin(admin, roleIds);
        return new ResultMessage();
    }

    /**
     * 添加管理员用户
     *
     * @param adminNew 管理员对象
     */
    @RequestMapping(value = "/addAdmin", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage addAdmin(Admin adminNew, @RequestParam(value = "roleIds[]") String[] roleIds) {
        adminService.addAdmin(adminNew, roleIds);
        return new ResultMessage();
    }

    /**
     * 删除管理员用户
     *
     * @param admin 管理员对象
     * @return ResultMessage
     */
    @RequestMapping(value = "/deleteAdmin", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage deleteAdmin(Admin admin) {
        adminService.deleteAdmin(admin);
        return new ResultMessage();
    }

    /**
     * 管理员登陆
     *
     * @param account  管理员用户名
     * @param password 管理员密码
     */
    @RequestMapping(value = "/adminLogin", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage<String> adminLogin(String account, String password) {
        if (!StringUtils.hasText(account) || !StringUtils.hasText(password)) {
            return new ResultMessage<String>().toFailure("账号和密码不能为空。");
        }
        //使用私钥解密字符串
        password = RSAEncryptor.decryptString(password);

        // 加密盐为系统毫秒 仅10秒内有效
        int index = password.indexOf('-');
        if (index < 1) {
            return new ResultMessage<String>().toFailure("无效密码，请重试。");
        }
        if (System.currentTimeMillis() - Long.valueOf(password.substring(0, index)) > 10000) {
            return new ResultMessage<String>().toFailure("登陆超时，请重试。");
        }

        // 取真正的密码部分验证
        password = password.substring(index + 1);
        Admin admin = adminService.adminLogin(account, password);
        if (admin == null) {
            return new ResultMessage<String>().toFailure("账号或密码不正确。");
        }

        String token = JWTUtils.generateToken("exp", JWTUtils.daysExp(3), UserConst.USER_ID_KEY, admin.getAdminId());
        return new ResultMessage<>(token);
    }

    /**
     * 获取当前登陆用户名
     */
    @RequestMapping(value = "/adminGetUserName", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage<String> adminGetUserName(@RequestHeader(UserConst.TOKEN_KEY) String token) {
        String adminId = JWTUtils.getTokenUserId(token);
        // 获取当前登陆的管理员名称
        Admin admin = adminService.findByAdminId(adminId);
        return new ResultMessage<>(admin.getName());
    }

    /**
     * 管理员重置密码。
     *
     * @param oldPassword 管理员原密码
     * @param newPassword 管理员新密码
     */
    @RequestMapping(value = "/resetPassword", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage resetPassword(@RequestHeader(UserConst.TOKEN_KEY) String token, String oldPassword, String newPassword) {
        String adminId = JWTUtils.getTokenUserId(token);
        adminService.resetPassword(adminId, oldPassword, newPassword);
        return new ResultMessage();
    }

    /**
     * 获取管理员菜单
     */
    @ResponseBody
    @RequestMapping(value = "/getAuthorityMenus", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage<List<Authority>> getAuthorityMenus(@RequestHeader(UserConst.TOKEN_KEY) String token) {
        String adminId = JWTUtils.getTokenUserId(token);
        // 根据管理员ID获取管理员所有权限
        List<Authority> authorities = adminService.getAuthorityMenus(adminId);
        return new ResultMessage<>(authorities);
    }

    /**
     * 管理员添加用户。
     */
    @ApiOperation("管理员添加用户")
    @RequestMapping(value = "/addUser", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage addUser(User user) {
        userService.adminAddUser(user);
        return new ResultMessage();
    }

    /**
     * 管理员查找用户并分页。
     */
    @RequestMapping(value = "/findUsers", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("管理员查找用户并分页（无须统计总数时count传false可提高查询效率）")
    public ResultMessage<Page<User>> findUsers(Paging paging, FindUserParam findUserParam) {
        return new ResultMessage<>(userService.adminFindUsers(paging, findUserParam));
    }

    /**
     * 管理员导出用户并分页。
     */
    @RequestMapping(value = "/exportUsers", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation("管理员导出用户并分页（必须限制导出条数，默认100，该接口不统计总数）")
    public void exportUsers(HttpServletResponse response, Paging paging, FindUserParam findUserParam) {
        paging.setCount(false);
        Page<User> userPage = userService.adminFindUsers(paging, findUserParam);
        List<ExportUser> exportUsers = userPage.getContent()
                .stream().map(user -> {
                    ExportUser exportUser = new ExportUser();
                    BeanUtils.copyProperties(user, exportUser);
                    String gender = user.getGender() == null ? null
                            : user.getGender() == 1 ? "男"
                            : user.getGender() == 2 ? "女" : "保密";
                    exportUser.setGender(gender);
                    return exportUser;
                }).collect(Collectors.toList());
        ExcelUtils.exportToResponse(response, "用户导出",
                ExportUser.class, exportUsers);
    }

    /**
     * 管理员修改用户信息。
     */
    @ApiOperation("管理员修改用户信息（只传需要修改的参数）")
    @RequestMapping(value = "/adminUpdateUser", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage adminUpdateUser(UserBasicInfo updateUser) {
        userService.setUserBasicInfo(updateUser, null);
        return new ResultMessage();
    }

    /**
     * 管理员统计用户信息。
     */
    @ApiOperation("管理员统计用户信息")
    @RequestMapping(value = "/userStatistics", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultMessage<UserStatistics> userStatistics() {
        return new ResultMessage<>(userService.userStatistics());
    }

}

 